<?php

class vector
{

    static function merge_values($array1, $array2)
    {
        $result = $array1;
        foreach ( $array2 as $value ) {
            if (!in_array($value, $array1)) {
                $result[] = $value;
            }
        }
        return $result;
    }

    static function merge($array1, $array2)
    {
        return array_merge(&$array1, &$array2);
    }

    static function key_exists($key, $array)
    {
        return array_key_exists(&$key, &$array);
    }

    static function implode($glue = null, $pieces)
    {
        return implode(&$glue, &$pieces);
    }

    static function sort(&$array)
    {
        return asort($array);
    }

    static function ksort(&$array)
    {
        return ksort($array);
    }

    static function sort_by_fn(&$array, $fn)
    {
        if (!function_exists($fn)) {
            return null;
        }
        vector::sort($array);
        $array_by_fn = array ();
        $min = vector::min($array);
        $max = vector::max($array);
        $diff = $max - $min;
        $dx = 1/(count($array));
        $x = $dx/2;
        for ($i=0; $i<count($array); $i++) {
            $array_by_fn[] = $fn($x);
            $x += $dx;
        }
        $diffs = array ();
        foreach ( $array as $key => $value ) {
            $diffs[$key] = array ();
            foreach ( $array_by_fn as $i => $y ) {
                $tmp_value = ($value-$min)/$diff;
                $dif = $tmp_value-$y;
                $diffs[$key][$i] = $dif*$dif;
            }
        }
        $array1 = array ();
        $tmp = array_keys($array_by_fn);
        foreach ( $array as $key => $value ) {
            $last_diffs = array ();
            foreach ( $tmp as $i ) {
                $last_diffs[$i] = $diffs[$key][$i];
            }
            vector::sort($last_diffs);
            reset($last_diffs);
            list($i, $null) = each($last_diffs);
            $array1[$i] = $key;
            unset($tmp[$i]);
        }
        $last_array = array ();
        for ( $i=0; $i<count($array1); $i++ ) {
            $last_array[$array1[$i]] = $array[$array1[$i]];
        }
        $array = $last_array;
    }

    static function revers(&$array)
    {
        $array = array_reverse($array, true);
    }

    static function min($array)
    {
        return min($array);
    }

    static function max($array)
    {
        return max($array);
    }

}

?>